package org.jeecg.modules.clue.job;


import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.clue.bo.CarBrand;
import org.jeecg.modules.clue.bo.CarBrandLetterGroup;
import org.jeecg.modules.clue.enums.RedisKey;
import org.jeecg.modules.message.handle.impl.EmailSendMsgHandle;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;

@Component
@Slf4j
@DisallowConcurrentExecution
public class ThirdDataJob implements Job {

    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource(name = "clueMailAccount")
    private MailAccount mailAccount;
    /**
     * 若参数变量名修改 QuartzJobController中也需对应修改
     */
    private String parameter;

    public void setParameter(String parameter) {
        this.parameter = parameter;
    }


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("ThirdDataJob 定时任务");




        getBrandSeriesData();

    }

    private void getBrandSeriesData() {
        try {
            String url = "https://caropen.api.autohome.com.cn/v1/carprice/tree_menu";
            HttpRequest request = HttpUtil.createGet(url);
            HttpResponse execute = request.execute();
            String body = execute.body();
            JSONObject bodyJson = JSONObject.parseObject(body);
            if (0 == bodyJson.getInteger("returncode")) {
                JSONArray resultArray = bodyJson.getJSONArray("result");

                ArrayList<CarBrandLetterGroup> letterGroups = new ArrayList<>();



                if (null != resultArray && !resultArray.isEmpty()) {
                    for (Object wordGroupObj : resultArray) {
                        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(wordGroupObj));
                        CarBrandLetterGroup group = new CarBrandLetterGroup();
                        group.setFirstletter(jsonObject.getString("firstletter"));

                        ArrayList<CarBrand> carBrands = new ArrayList<>();

                        JSONArray branditems = jsonObject.getJSONArray("branditems");
                        if (null != branditems && !branditems.isEmpty()){
                            for (Object branditemObj : branditems) {
                                JSONObject branditemJSON = JSON.parseObject(JSON.toJSONString(branditemObj));
                                CarBrand carBrand = new CarBrand();
                                carBrand.setId(branditemJSON.containsKey("id")?branditemJSON.getString("id"):"");
                                carBrand.setLogo(branditemJSON.containsKey("logo")?branditemJSON.getString("logo"):"");
                                carBrand.setName(branditemJSON.containsKey("name")?branditemJSON.getString("name"):"");
                                carBrand.setFctitems(branditemJSON.containsKey("fctitems")?branditemJSON.getJSONArray("fctitems"):new JSONArray());

                                String logo = branditemJSON.getString("logo");
                                log.info("解析 logo {}",logo);
                                if (StringUtils.isNotBlank(logo)) {
                                    String base64Img = convertImageToBase64(logo);
                                    log.info("logoBase64 {}",base64Img);
                                     carBrand.setLogoBase64(null != base64Img?base64Img:"");

                                }

                                carBrands.add(carBrand);
                            }

                        }
                        group.setBranditems(carBrands);
                        letterGroups.add(group);
                    }
                    stringRedisTemplate.opsForValue().set(RedisKey.CarBrandSeries.key, JSONObject.toJSONString(letterGroups));
                    String send = Mail.create(mailAccount)
                            .setTos(mailAccount.getUser())
                            .setTitle("获取汽车之家品牌车系数据成功")
                            .setContent( resultArray.toJSONString())
                            .send();
                    log.info("邮件发送结果 {}",send);
                    return;
                }

            }
            String send = Mail.create(mailAccount)
                    .setTos(mailAccount.getUser())
                    .setTitle("获取汽车之家品牌车系数据失败")
                    .setContent(bodyJson.toJSONString())
                    .send();
            log.info("邮件发送结果 {}",send);
        } catch (HttpException e) {
            log.error(e.getMessage());
            String send = Mail.create(mailAccount)
                    .setTos(mailAccount.getUser())
                    .setTitle("获取汽车之家品牌车系数据失败")
                    .setContent(e.getMessage())
                    .send();
            log.info("邮件发送结果 {}",send);

        }


    }
    /**
     * 将指定URL的图片转换为Base64编码字符串
     * 使用时 data:image/png;base64,  拼接上
     * @param imageUrl 图片的URL
     * @return Base64编码字符串，如果请求失败则返回null
     */
    public static String convertImageToBase64(String imageUrl) {
        try {
            // 创建GET请求
            HttpRequest request = HttpRequest.get(imageUrl);
            request.contentType("image/png");

            // 执行请求并获取响应
            HttpResponse response = request.execute();

            // 检查响应码是否为200（HTTP_OK）
            if (response.isOk()) {
                // 获取响应体中的字节数组
                byte[] imageBytes = response.bodyBytes();

                // 将字节数组转换为Base64编码字符串
                return Base64.getEncoder().encodeToString(imageBytes);
            } else {
                log.error("Failed to fetch the image. HTTP response code: " + response.getStatus());
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
